//引入各种插件
const gulp = require("gulp");
const htmlmin = require("gulp-htmlmin");
const autoprefixer = require("gulp-autoprefixer");
const cssmin = require("gulp-cssmin");
const babel = require("gulp-babel");
const uglify = require("gulp-uglify");
const clean = require("gulp-clean");
const webserver = require("gulp-webserver");
const sasschina = require("gulp-sass-china");
//1.转存主页面（没有压缩）
function indexFn(){
	return gulp.src("./src/index.html")
			.pipe(gulp.dest("./dist/"))
}
exports.index = indexFn;
//2.转存并压缩各种html页面
function htmlFn(){
	return gulp.src("./src/pages/**/*")
			.pipe(htmlmin({
				removeEmptyAttributes:true,
				collapseWhitespace:true
			}))
			.pipe(gulp.dest("./dist/pages"))
}
exports.html = htmlFn;
//3.静态资源直接转存（不需要压缩）
function staticFn(){
	return gulp.src("./src/static/**/*")
			.pipe(gulp.dest("./dist/static"))
}
exports.static = staticFn;
//4.1转存并压缩css文件
function cssFn(){
	return gulp.src("./src/css/**/*")
			.pipe(autoprefixer("last 2 version","ie 8","ie 9","opera 12.1","android 4","safari 5","iso 6"))
			.pipe(cssmin())
			.pipe(gulp.dest("./dist/css"))
}
exports.css = cssFn;
//4.2处理sass文件
function sassFn(){
	return gulp.src("./src/sass/**/*")
			.pipe(sasschina())
			.pipe(autoprefixer("last 2 version","ie 8","ie 9","safari 5","opera 12.1","iso 6","android 4"))
			.pipe(cssmin())
			.pipe(gulp.dest("./dist/css"))
}
exports.sass = sassFn;
//5.转存并压缩js文件
function jsFn(){
	return gulp.src("./src/js/**/*")
			.pipe(babel({
				presets:["@babel/env"]
			}))
			.pipe(uglify())
			.pipe(gulp.dest("./dist/js"))
}
exports.js = jsFn;
//6.创建服务器
function webserverFn(){
	return gulp.src("./dist")
			.pipe(webserver({
				host:"localhost",
				port:"85",
				livereload:true,
				open:"./index.html",
				proxies:[{
					source:"/testUrl",
					target:"https://wanandroid.com/wxarticle/chapters/json"
				}]
			}))
}
exports.server = webserverFn;
//7.监听所有文件
function watchAllFn(release){
	gulp.watch("./src/index.html",indexFn);
	gulp.watch("./src/static/**/*",staticFn);
	gulp.watch("./src/pages/**/*",htmlFn);
	gulp.watch("./src/css/**/*",cssFn);
	gulp.watch("./src/sass/**/*",sassFn);
	gulp.watch("./src/js/**/*",jsFn);
	//传入参数release，释放结束信号
	release();
}
exports.watchAll = watchAllFn;
//8.终极打包
exports.all = gulp.series(gulp.parallel(indexFn,staticFn,htmlFn,cssFn,sassFn,jsFn),gulp.parallel(watchAllFn,webserverFn));
